const path = require("path");
const webpack = require('webpack')
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const SpeedMeasurePlugin = require("speed-measure-webpack-plugin");
const AddAssetHtmlPlugin = require('add-asset-html-webpack-plugin')
const test = require("node:test");
const smp = new SpeedMeasurePlugin({
  disable: !(process.env.MEASURE === 'true'),
  outputFormat: 'humanVerbose',
});
const glob = require("glob");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const { PurgeCSSPlugin } = require("purgecss-webpack-plugin");

const PATHS = {
  src: path.join(__dirname, "src"),
};

module.exports = {
  publicPath: process.env.NODE_ENV === 'production' ? './' : './',
  parallel: true,
  configureWebpack: smp.wrap({
    cache: {
      type: 'filesystem',
      cacheDirectory: path.resolve(__dirname, './node_modules/.cache_temp'),
      name: 'vue2-elm'
    },
    resolve: {
      alias: {
        'src': path.resolve(__dirname, './src'),
        'assets': path.resolve(__dirname, './src/assets'),
        'components': path.resolve(__dirname, './src/components')
      }
    },
    module: {
      rules: [
        {
          test: /\.js$/,
          exclude: /node_modules/,
          use: {
            loader: 'thread-loader',
            options: {
              workers: require('os').cpus().length - 1
              // workers: 2
            }
          }
        },
        {
          test: /\.(png|gif|jpe?g|svg|webp)$/i,
          use: [
            {
              loader: 'image-webpack-loader',
              options: {
                disable: true,
                mozjpeg: {
                  progressive: true,
                },
                // optipng.enabled: false will disable optipng
                optipng: {
                  enabled: false,
                },
                pngquant: {
                  quality: [0.65, 0.90],
                  speed: 4
                },
                gifsicle: {
                  interlaced: false,
                },
                // the webp option will enable WEBP
                webp: {
                  quality: 7
                }
              }
            }
          ]
        }
      ]
    },
    plugins: [
      new BundleAnalyzerPlugin({
        analyzerMode: 'server', // 不启动打包报告
      }),
      new webpack.DllReferencePlugin({
        context: __dirname,
        manifest: path.resolve(__dirname, './dll/vue-manifest.json')
      }),
      new AddAssetHtmlPlugin({
        filepath: path.resolve(__dirname, './dll/vue.dll.js')
      }),
      new PurgeCSSPlugin({
        paths: glob.sync(`${PATHS.src}/**/*`, { nodir: true }),
      }),
    ]
  }),

}
